#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

//进程程序替换

int main()
{
  pid_t id = fork();
  if(id == 0)
  {
    char*  argv[] = 
    {
      "ls",
      "-a",
      "-l",
      NULL
    };

    char* argvForEnv[] =
    {
      "testEnv",
      NULL
    };

    char* const myenv[] = 
    {
      "HI=You Can See Me",
      NULL
    };

    printf("我是子进程，pid:%d ppid:%d\n 准备替换系统级程序\n", getpid(), getppid());
    sleep(1);

    //execl("/bin/ls", "ls", "-a", "-l", NULL); //函数1
    //execv("/bin/ls", argv); //函数2
    
    //execlp("ls", "ls", "-a", "-l", NULL); //函数3
    //execvp("ls", argv); //函数4
   
    extern char** environ;

    //execle("./otherFile/testEnv", NULL, myenv); //函数5
    //putenv("HI=You Can See Me");
    //execle("./otherFile/testEnv", NULL, environ); //最后一个参数，如果不主动传，则为空

    //execvpe("testEnv",argvForEnv, myenv);  //函数6 
    //putenv("HI=You Can See Me");
    //execvpe("testEnv",argvForEnv, environ);
    
    execve("/bin/ls", argv, environ); //函数7，系统真正提供的函数
    
    exit(2);
  }

  int status = 0;
  pid_t ret = waitpid(id, &status, 0);  //父进程阻塞等待

  if(ret < 0)
  {
    printf("子进程不存在！\n");
    exit(-1);
  }
  else if(ret == 0)
  {
    printf("子进程正在运行\n");
  }
  else
  {
    //此时子进程运行结束，轮到父进程运行
    if(!WIFEXITED(status))
    {
      printf("子进程因终止信号而终止，exit_signal:%d code dump:%d\n", status & 0x7F, (status >> 7) & 1);
    }
    else if(WEXITSTATUS(status) == 2)
    {
      printf("子进程程序替换失败，返回错误结果，exit_code:%d\n", WEXITSTATUS(status));
    }
    else
    {
      printf("子进程正常运行，exit_code:%d\n", WEXITSTATUS(status));
    }
  }

  return 0;
}
  
